package eu.carbones.auth;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import org.springframework.extensions.surf.site.AuthenticationUtil;

/*
 *  Simple filter that redirects to the login page
 *  if the user is not authenticated. 
 */

public class BasicAuthenticationFilter implements Filter {
 
    public void doFilter(ServletRequest sreq, ServletResponse sres, FilterChain chain)
    		throws IOException, ServletException 
    {
    	HttpServletRequest req = (HttpServletRequest) sreq;
        HttpServletResponse res = (HttpServletResponse) sres;
        
        if (AuthenticationUtil.isAuthenticated(req))
        {
        	chain.doFilter(req, res);
        }
        else res.sendRedirect(req.getContextPath() + "/login/" + "?page=" + req.getRequestURI());   
    }
    public void init(FilterConfig config) throws ServletException {
       
    }
    public void destroy() {
    }   
}